package com.bwie.auth.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwie.auth.feign.AuthFeignService;
import com.bwie.auth.service.AuthService;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.SysUser;
import com.bwie.common.domain.request.SysUserRequest;
import com.bwie.common.domain.response.JwtResponse;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: AuthServiceImpl
 * @Description:
 * @Author: 平安
 * @Date: 2024/4/25 9:17:01
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private AuthFeignService authFeignService;

    @Autowired
    private RedisTemplate<String ,String > redisTemplate;

    @Autowired
    private HttpServletRequest request;

    @Override
    public Result<JwtResponse> login(SysUserRequest sysUserRequest) {

        if (sysUserRequest.getUsername() == null || sysUserRequest.getUsername().equals("")){
            return Result.error("用户名不能为空");
        }
        if (sysUserRequest.getPassword() == null || sysUserRequest.getPassword().equals("")){
            return Result.error("密码不能为空");
        }
        Result<SysUser> sysUserByUsername = authFeignService.findSysUserByUsername(sysUserRequest.getUsername());
        SysUser sysUser = sysUserByUsername.getData();
        if (sysUser == null){
            return Result.error("用户信息不存在，请先注册");
        }
        if (!sysUserRequest.getPassword().equals(sysUser.getPassword())){
            return Result.error("密码错误，请重新输入");
        }
        // 验证成功 ===》 登录
        HashMap<String, Object> map = new HashMap<>();
        String userKey = UUID.randomUUID().toString().replaceAll("-", "");
        map.put(JwtConstants.USER_KEY,userKey);
        String token = JwtUtils.createToken(map);

        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+userKey, JSONObject.toJSONString(sysUser),15, TimeUnit.MINUTES);

        JwtResponse jwtResponse = new JwtResponse();
        jwtResponse.setToken(token);
        jwtResponse.setExpireTimeStr("15MIN");

        return Result.success(jwtResponse);
    }

    @Override
    public SysUser info() {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        String userJSON = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        return JSONObject.parseObject(userJSON,SysUser.class);
    }
}
